package com.up4years.dataapi.service.weixin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.http.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.up4years.dataapi.entity.weixin.Button;
import com.up4years.dataapi.entity.weixin.Menu;
import com.up4years.dataapi.service.base.BaseManager;

@Service
public class WeixinMenuService {
	@Autowired
	private BaseManager baseManager;
	
	public boolean createMenus(HttpServletRequest request){

 		JSONObject menus = JSONObject.fromObject(this.getMenus(request));
		int result=-1;
		try {
			result = WeixinService.createMenu(WeixinService.getAccessToken().getToken(), menus.toString());
		} catch (ParseException e) {
 			e.printStackTrace();
		} catch (IOException e) {
 			e.printStackTrace();
		}
		return result==0;
	}
	private Menu getMenus(HttpServletRequest request){
		String basePath = request.getScheme() + "://" + request.getServerName() + request.getContextPath() + "/";
	//	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ request.getContextPath() + "/";
		Menu menu = new Menu();
		List<Button> list = this.baseManager.query("Button.getAllButtons", new HashMap<String,Object>());
		Map<String, Button> map = new HashMap<String, Button>();
		/**一级 二级 三级菜单**/
		Map<String, Button> map1 = new HashMap<String, Button>();
		Map<String, Button> map2 = new HashMap<String, Button>();
		Map<String, Button> map3 = new HashMap<String, Button>();
		for(int i=0;i < list.size();i++){
			Button button = list.get(i);
			//处理openid事件
			button.setUrl(WeixinService.generateURL(basePath+"/weixin/jump.htm", button.getUrl(), button.getUseopenid()==1));
			map.put(button.getId().toString(), button);
			//一级菜单
			if(button.getLevel()==1){
				map1.put(button.getId().toString(), button);
			}else if(button.getLevel()==2){
				map2.put(button.getId().toString(), button);
			}else if(button.getLevel()==3){
				map3.put(button.getId().toString(), button);
			}
		}
		
		Iterator<Entry<String, Button>> it3 = map3.entrySet().iterator();
		while(it3.hasNext()){
			Button button = it3.next().getValue();
			map2.get(button.getPid().toString()).addButton(button);
		}
		Iterator<Entry<String, Button>> it2 = map2.entrySet().iterator();
		while(it2.hasNext()){
			Button button = it2.next().getValue();
			map1.get(button.getPid().toString()).addButton(button);
		}

		menu.setButton(new ArrayList<Button>(map1.values()));
		return menu;
	}
}
